package com.it.office.masster.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.it.office.common.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.nio.file.Files;
import java.util.HashMap;

/**
 * @author jimy
 * @时间 2023年5月5日15:35:56
 * @描述 编辑word文档的controller
 */
@RestController
@RequestMapping("word")
public class WordOfficeController {

    //读取本地模板
    @Value("template/template.docx")
    ClassPathResource classPathResource;


    /**
     *
     * @return 将最后的效果返回给docx文件
     * @throws IOException 抛出异常
     */
    @PostMapping("/to-docx")
    public JsonResult<String> toDocx() throws IOException {
        //获取本地模板流
        InputStream inputStream = classPathResource.getInputStream();
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(
                new HashMap<String, Object>(){{
                    put("title", "title替换成功");
                }});
        template.writeAndClose(Files.newOutputStream(new File("f:\\Users\\Administrator\\Desktop\\新建 DOCX 文档.docx").toPath()));
        inputStream.close();
        return new JsonResult<>(1,"编译模板成功!");
    }

    /**
     * @描述 将模板的数据放到响应对象的 流 里面
     * @param response 响应对象
     */
    @PostMapping("to-bytes")
    public void toBytes(HttpServletResponse response) throws IOException {
        //获取本地模板流
        InputStream inputStream = classPathResource.getInputStream();
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(
                new HashMap<String, Object>(){{
                    put("title", "title替换成功");
                }});
        ServletOutputStream outputStream = response.getOutputStream();
        template.writeAndClose(outputStream);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }
}
